import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:happy_elf_app/apis/home.dart';
import 'package:happy_elf_app/store/config.dart';
import 'package:happy_elf_app/store/home.dart';
import 'package:happy_elf_app/utils/adaption.dart';
import 'package:happy_elf_app/utils/globalKey.dart';
import 'package:happy_elf_app/utils/themColor.dart';
import 'package:happy_elf_app/views/Main/index.dart';
import 'package:happy_elf_app/widgets/headerBack/index.dart';

class Evolution extends StatefulWidget {
  const Evolution({super.key});

  @override
  State<Evolution> createState() => _EvolutionState();
}

final HomeDataProvider =
    Provider.of<HomeData>(Global.navigatorKey.currentContext!, listen: false);

class _EvolutionState extends State<Evolution>
    with SingleTickerProviderStateMixin {
  late AnimationController _controller;

  int page = 1; // 1是初始状态 2是进化状态
  List phase = [
    {'title': '初期阶段', 'value': 1},
    {'title': '中期阶段', 'value': 2},
    {'title': '后期阶段', 'value': 3},
    {'title': '终极阶段', 'value': 4}
  ];
  int active = 0;
  Map elfInit = {}; // 精灵数据

  @override
  void initState() {
    super.initState();
    initData();
    _controller = AnimationController(vsync: this);
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

  void initData() async {
    if (HomeDataProvider.target['id'] == null) {
      // 没有选目标
    } else {
      // 选了目标直接改为精灵进化
      getElf();
    }
  }

  void getElf() async {
    var res = await Home().getElfData(HomeDataProvider.target['id']);
    print('1111$res');
    if (res['code'] == 200) {
      page = 2;
      elfInit = res['data'];
      active = res['data']['currentStageNo'];
    }
    setState(() {});
  }

  Widget evolutionBuild() {
    final int progress = elfInit['progress'];
    final int currentStageNo = elfInit['currentStageNo'];
    final double stageStartPercentage = (currentStageNo - 1) * 25.0;
    final double currentProgressInStage =
        (progress - stageStartPercentage).clamp(0.0, 25.0);
    final double fillRatio = currentProgressInStage / 25.0;
    final double progressBarWidth = fillRatio * 85.0;
    print('当前阶段: $currentStageNo');
    print('当前进度在阶段内: $currentProgressInStage%');
    print('填充比例: $fillRatio');
    print('进度条宽度: $progressBarWidth px');
    return Padding(
      padding: const EdgeInsets.symmetric(horizontal: 12),
      child: Column(
        children: [
          Row(
            // mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              ...phase.map(
                (e) => Container(
                  width: 85,
                  height: 32,
                  margin: EdgeInsets.only(left: e['value'] == 0 ? 0 : 7),
                  decoration: BoxDecoration(
                      borderRadius: BorderRadius.circular(4),
                      color: hexColor('#ffffff'),
                      boxShadow: const [
                        BoxShadow(
                          color: Color.fromRGBO(0, 0, 0, 0.2),
                          blurRadius: 2.93,
                          offset: Offset(0, 0),
                          spreadRadius: 0,
                        )
                      ]),
                  child: Stack(
                    children: [
                      if (e['value'] <= currentStageNo)
                        Container(
                          width: e['value'] < currentStageNo
                              ? 85
                              : progressBarWidth,
                          height: 32,
                          decoration: BoxDecoration(
                            borderRadius: BorderRadius.circular(4),
                            color: hexColor('#e9614d'),
                          ),
                        ),
                      Padding(
                        padding: const EdgeInsets.only(left: 12, top: 4),
                        child: Text(
                          e['title'],
                          style: TextStyle(
                              color: hexColor(e['value'] <= currentStageNo
                                  ? '#f5f5f5'
                                  : '#666666')),
                        ),
                      ),
                    ],
                  ),
                ),
                // ),
              )
            ],
          ),
          Container(
            width: 370,
            height: 560,
            margin: EdgeInsets.only(top: 12),
            decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(20),
                border: Border.all(width: 1.px, color: hexColor('#8888888'))),
            child: Column(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                SizedBox(height: 24),
                Image.network(elfInit['imageUrl'], height: 420),
                elfInit['canEvolve']
                    ? Padding(
                        padding: const EdgeInsets.symmetric(vertical: 16),
                        child: TextButton(
                            style: TextButton.styleFrom(
                              backgroundColor: hexColor('#E9614D'),
                              padding: const EdgeInsets.symmetric(
                                  horizontal: 50, vertical: 10),
                            ),
                            onPressed: () {
                              // 点击生成
                              showTaskDialog(context);
                            },
                            child: Text(
                              '立即进化',
                              style: TextStyle(color: hexColor('#ffffff')),
                            )),
                      )
                    : SizedBox(
                        height: 24,
                      ),
              ],
            ),
          )
        ],
      ),
    );
  }

  void showBadge(BuildContext context, data) {
    showDialog(
        context: context,
        builder: (BuildContext context) {
          return StatefulBuilder(builder: ((context, dialogSetState) {
            return Align(
              child: Container(
                width: 280,
                height: 140,
                alignment: Alignment.center,
                padding: EdgeInsets.symmetric(vertical: 24),
                decoration: BoxDecoration(
                    color: hexColor('#ffffff'),
                    borderRadius: BorderRadius.circular(12)),
                child: Column(
                  children: [
                    Text('恭喜获得进化徽章'),
                    Text('(精灵名字 ${phase[active - 1]['title']})'),
                    SizedBox(height: 24),
                    Image.network(
                      data['badgeImageUrl'],
                      width: 280,
                    ),
                    GestureDetector(
                      onTap: () {
                        getElf();
                      },
                      child: Container(
                          padding: const EdgeInsets.symmetric(
                              horizontal: 24, vertical: 2),
                          decoration: const BoxDecoration(
                              color: Colors.white,
                              boxShadow: [
                                BoxShadow(
                                  color: Color.fromRGBO(199, 195, 195, 0.5),
                                  blurRadius: 2.93,
                                  offset: Offset(0, 0),
                                  spreadRadius: 0,
                                )
                              ]),
                          child: Text('关闭')),
                    )
                  ],
                ),
              ),
            );
          }));
        });
  }

  void showTaskDialog(BuildContext context) {
    showDialog(
        context: context,
        builder: (BuildContext context) {
          return StatefulBuilder(builder: ((context, dialogSetState) {
            return Align(
              child: Container(
                width: 280,
                height: 140,
                alignment: Alignment.center,
                padding: EdgeInsets.symmetric(vertical: 24),
                decoration: BoxDecoration(
                    color: hexColor('#ffffff'),
                    borderRadius: BorderRadius.circular(12)),
                child: Column(
                  children: [
                    Text(
                      '能量已满,是否开启进化?',
                      style:
                          TextStyle(color: hexColor('#333333'), fontSize: 16),
                    ),
                    SizedBox(height: 36),
                    Row(
                      crossAxisAlignment: CrossAxisAlignment.center,
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        SizedBox(width: 2),
                        GestureDetector(
                          onTap: () {
                            Navigator.of(context).pop();
                          },
                          child: Container(
                              padding: const EdgeInsets.symmetric(
                                  horizontal: 24, vertical: 2),
                              decoration: const BoxDecoration(
                                  color: Colors.white,
                                  boxShadow: [
                                    BoxShadow(
                                      color: Color.fromRGBO(199, 195, 195, 0.5),
                                      blurRadius: 2.93,
                                      offset: Offset(0, 0),
                                      spreadRadius: 0,
                                    )
                                  ]),
                              child: Text('稍后')),
                        ),
                        GestureDetector(
                          onTap: () async {
                            var res = await Home()
                                .changePregress(HomeDataProvider.target['id']);
                            EasyLoading.show(status: '加载中...');
                            if (res['data'] == 200) {
                              EasyLoading.dismiss();
                              Navigator.of(context).pop();
                              showBadge(context, res['data']);
                            }
                          },
                          child: Container(
                              padding: const EdgeInsets.symmetric(
                                  horizontal: 24, vertical: 2),
                              decoration: const BoxDecoration(
                                  color: Colors.white,
                                  boxShadow: [
                                    BoxShadow(
                                      color: Color.fromRGBO(199, 195, 195, 0.5),
                                      blurRadius: 2.93,
                                      offset: Offset(0, 0),
                                      spreadRadius: 0,
                                    )
                                  ]),
                              child: Text('开启')),
                        ),
                        SizedBox(width: 2),
                      ],
                    )
                  ],
                ),
              ),
            );
          }));
        });
  }

  Widget initial() {
    return Column(
      children: [
        Image.asset('lib/assets/images/space/generate.png', height: 520),
        SizedBox(height: 24),
        TextButton(
            style: TextButton.styleFrom(
              backgroundColor: hexColor('#E9614D'),
              padding: const EdgeInsets.symmetric(horizontal: 50, vertical: 10),
            ),
            onPressed: () {
              // 点击生成 去第一个页面
              // page = 2;
              // setState(() {});
              Navigator.pushReplacement(
                context,
                MaterialPageRoute(builder: (context) => MainPage()),
              );
            },
            child: Text(
              '立即生成',
              style: TextStyle(color: hexColor('#ffffff')),
            ))
      ],
    );
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      child: Column(
        children: [
          HeaderBack(
              title: page == 1 ? '梦想精灵' : '进化空间',
              isFirst: page != 1,
              callback: () {
                page -= 1;
                setState(() {});
              }),
          page == 1 ? initial() : evolutionBuild()
        ],
      ),
    );
  }
}
